import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import store from '@/store'
Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import( /* webpackChunkName: "goods" */ '../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'user',
    redirect:'/user/cart',
    // 路由独享守卫
    // beforeEnter: (to, from, next)=>{
    //   let token = localStorage.getItem('x-auth-token')
    //       if (token) {
    //         next()
    //       } else {
    //         // 提示没有登录
    //         store.dispatch("showToast/asyncchangeIsShowToast", {
    //           isShow: true,
    //           msg: "你还没有登录！",
    //           type: "danger",
    //         });
    //       }
    // },
    component: () => import( /* webpackChunkName: "user" */ '../views/User.vue'),
    children: [
      {
        path: 'cart',
        component: () => import( /* webpackChunkName: "cart" */ '../components/user/Cart.vue'),
      }
    ]
  },
  {
    path: '/order',
    name: 'order',
    component: () => import( /* webpackChunkName: "order" */ '../views/Order.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import( /* webpackChunkName: "free" */ '../views/Free.vue')
  },
  {
    path: '/details',
    name: 'details',
    component: () => import( /* webpackChunkName: "details" */ '../views/Details.vue')
  },
  {
    path: '*',
    name: 'error',
    component: () => import( /* webpackChunkName: "error" */ '../components/Error.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局导航守卫
// router.beforeEach((to, from, next) => {
//   if (to.path == '/user') {
//     let token = localStorage.getItem('x-auth-token')
//     if (token) {
//       next()
//     } else {
//       // 提示没有登录
//       store.dispatch("showToast/asyncchangeIsShowToast", {
//         isShow: true,
//         msg: "你还没有登录！",
//         type: "danger",
//       });
//     }
//     return
//   }
//   next()
// })

// 解决连续点击报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router